package dao

import (
	"github.com/astaxie/beego/orm"
	"goblog/models"
)

func Count(sql string, args []interface{}, dao orm.Ormer) int {
	temp := "select count(1) from (" + sql + ") temp";
	var count int
	dao.Raw(temp, args).QueryRow(&count)
	return count
}

func Paging(sql string, args []interface{}, term *models.Term, dao orm.Ormer) orm.RawSeter {
	term.Total = Count(sql, args, dao)
	term.TotalPage = term.Total / term.Size
	if term.Total%term.Size > 0 {
		term.TotalPage += 1
	}
	if term.Start() >= 0 {
		sql += " limit ?, ?"
		args = append(args, term.Start(), term.Size)
	} else {
		sql += " limit ?"
		args = append(args, term.Size)
	}
	return dao.Raw(sql, args)
}
